package com.itheima.controller.admin;

import com.itheima.entity.FileEntity;
import com.itheima.result.Result;
import com.itheima.util.AliOssUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@RequiredArgsConstructor
@Slf4j
public class UploadController {

    private final AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file){
        try {
            String originalFilename = file.getOriginalFilename();
            String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newfileName = UUID.randomUUID() + prefix;

            File fileNew = new File("C:\\Develop\\ydd\\nginx-youdianda\\html\\backend\\undefined\\" + newfileName);
//            String url = aliOssUtil.upload(file.getBytes(), newfileName);
            file.transferTo(fileNew);
            FileEntity fileEntity = new FileEntity();
            fileEntity.setSavePath("/"+newfileName);
            return Result.success(fileEntity);
        } catch (IOException e) {
            log.error("文件上传失败"+ e);
        }
        return Result.error("文件上传失败");
    }
}